//引入express模块
const express = require('express')
//创建路由器对象
const router = express.Router()
//引入连接池模块
const pool = require('../pool.js')
module.exports = router
/////////////////////////////////////////// 前端部分

// 前台获取宠物类别信息
router.get('/pets_var', (req, res) => {
    pool.query('select * from pets_var where sort=?',[req.query.sort], (err, r) => {
        if (err) {
            throw err
        }
        console.log(r)
        if (r.length == 0) {
            res.send({ code: 400, msg: '查询失败',data:r })
        } else {
            res.send({ code: 200, msg: '查询成功',data:r })
        }
    })
})

// 前台通过宠物类别获取宠物领养列表信息
router.get('/adoptlist', (req, res) => {
    pool.query('select * from (pets_detail left outer join pets_var on pets_detail.variety=pets_var.variety) where sort=? ',[req.query.sort], (err, r) => {
        if (err) {
            throw err
        }
        console.log(r)
        if (r.length == 0) {
            res.send({ code: 400, msg: '查询失败',data:r })
        } else {
            res.send({ code: 200, msg: '查询成功',data:r })
        }
    })
})

// 前台通过id获取宠物领养详细信息
router.get('/adoptdetailbyid', (req, res) => {
    pool.query('select * from pets_detail where id=?',[req.query.id], (err, r) => {
        if (err) {
            throw err
        }
        console.log(r)
        if (r.length == 0) {
            res.send({ code: 400, msg: '查询失败',data:r })
        } else {
            res.send({ code: 200, msg: '查询成功',data:r })
        }
    })
})
// 前台通过variety获取宠物领养列表信息
router.get('/adoptdetail', (req, res) => {
    pool.query('select * from pets_detail where variety=?',[req.query.variety], (err, r) => {
        if (err) {
            throw err
        }
        console.log(r)
        if (r.length == 0) {
            res.send({ code: 400, msg: '查询失败',data:r })
        } else {
            res.send({ code: 200, msg: '查询成功',data:r })
        }
    })
})
// 后台修改宠物信息
router.put('/pets_change', (req, res, next) => {
	//获取put传递的参数
	var obj = req.body
	console.log(obj)
	pool.query('update pets_detail set ? where id=?', [obj,obj.id], (err, r) => {
		if (err) {
			return next(err)
		}
		console.log(r)
		if (r.changedRows == 1) {
			res.send({ code: 200, msg: '修改成功' })
		} else {
			res.send({ code: 400, msg: '修改失败' })
		}
	})
})

// 后台删除宠物信息
router.delete('/:id', (req, res, next) => {
	pool.query('delete from pets_detail where id=?', [req.params.id], (err, r) => {
		if (err) {
			return next(err)
		}
		console.log(r)
		if (r.affectedRows == 0) {
			res.send({ code: 400, msg: '删除失败' })
		} else {
			res.send({ code: 200, msg: '删除成功' })
		}
	})
})

// 后台通过宠物类别获取宠物信息
router.get('/pets_detail', (req, res) => {
    pool.query('select * from pets_detail where category=?',[req.query.category], (err, r) => {
        if (err) {
            throw err
        }
        console.log(r)
        if (r.length == 0) {
            res.send({ code: 400, msg: '查询失败',data:r })
        } else {
            res.send({ code: 200, msg: '查询成功',data:r })
        }
    })
})